package DAO;



import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import Hibernate.HibernateUtil;
import Negocio.Envio;


public class HibernateEnvioDAO {
	
	private static HibernateEnvioDAO instancia = null;
	private static SessionFactory sf = null;
	
	
	public static HibernateEnvioDAO getInstancia(){
		if(instancia == null){
			instancia = new HibernateEnvioDAO();
			sf = HibernateUtil.getSessionFactory();
		}
		return instancia;
	}
	
	public void grabarEnvio(Envio envio){
		try{
		Session session = sf.openSession();
		session.beginTransaction();
		session.saveOrUpdate(envio);
		session.getTransaction().commit();
		session.flush();
		session.close();
		}catch(Exception e){
			System.out.println(e);
			System.out.println("Error al grabar un Envio");
		}
	}
	
	public void updateEnvio(Envio envio){
		try{
		Session session = sf.openSession();
		session.beginTransaction();
		session.saveOrUpdate(envio);
		session.flush();
		session.getTransaction().commit();
		session.close();
		}catch (Exception e){
			System.out.println(e);
            System.out.println("Error al actualizar un Envio");
		}
		
	}

	
	public Envio getEnvio(int id)
	{
        try 
        {
        	Session session=sf.openSession();
            session.beginTransaction();
            Query q = (Query) session.createQuery("from Envio e left join fetch e.encomiendas where e.idEnvio = ?").setInteger(0, id);
            Envio envio = (Envio) q.uniqueResult();

            session.getTransaction().commit();
            session.close();
            return envio;
        }
        catch (Exception e)
        {
            System.out.println(e);
            System.out.println("Error al cargar el Envio");
        }
        return null;
	}

}
